package com.itheima.reggie.controller;


import cn.hutool.core.io.IoUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.converters.longconverter.LongStringConverter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    @GetMapping("export")
    public void R(HttpServletResponse response) {
        try {
            response.setHeader("Content-Disposition",
                    "attachment; filename=employee.xlsx");
            //查询数据库中所有员工数据
            List<Employee> lists = employeeService.list();

            for (Employee list : lists) {
                Long createUserid = list.getCreateUser();
                Employee id = employeeService.getById(createUserid);
                Employee employee = employeeService.getById(id);
                list.setCrUser(employee.getName());

                Long updateUserid = list.getUpdateUser();
                Employee id1 = employeeService.getById(updateUserid);
                Employee employee1 = employeeService.getById(id1);
                list.setUpUser(employee1.getName());

            }
            ServletOutputStream outputStream = response.getOutputStream();
            EasyExcel.write(outputStream,Employee.class).registerConverter(new LongStringConverter()).
                    sheet("员工数据").doWrite(lists);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @PostMapping("/login")
    public R login(@RequestBody Employee employee, HttpSession session) {
        if (employee == null || StringUtils.isEmpty(employee.getUsername())
                || StringUtils.isEmpty(employee.getPassword())) {
            return R.error("用户名或密码不能为空");
        }
        //根据页面提交的用户名username查询数据库唯一索引
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        qw.eq(Employee::getUsername, employee.getUsername());
        Employee existEmp = employeeService.getOne(qw);

        if (existEmp == null) {
            return R.error("账号不存在");
        }

        if (existEmp.getStatus() == 0) {
            return R.error("账户已禁用！");
        }

        String password = existEmp.getPassword();//密文
        String password1 = employee.getPassword();//明文
        password1 = DigestUtils.md5DigestAsHex(password1.getBytes());

        if (password.equals(password1)) {
            //对比成功，返回code ：1和data ：用户信息
            //将用户数据存入会话中【session】 如何获取session
            existEmp.setPassword(null);
            session.setAttribute("loginUser", existEmp);
            return R.success(existEmp);
        }

        //对比关联失败 返回code 0 he msg 用户名和密码错误
        return R.error("用户名和密码错误");
    }

    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        request.getSession().removeAttribute("loginUser");
        return R.success("退出成功");
    }

    @PostMapping
    public R<String> save(HttpServletRequest request, @RequestBody Employee employee) {

        //设置初始密码为123456
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        /*employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        //获取当前用户的Id

        Employee loginUser = (Employee)request.getSession().getAttribute("loginUser");
        employee.setCreateUser(loginUser.getId());
        employee.setUpdateUser(loginUser.getId());*/
        //调用业务层
        employeeService.save(employee);
        return R.success("新增员工成功");

    }

    @GetMapping("/page")
    public R pageQuery(Integer page, Integer pageSize, String name) {
        log.info("page = {},pagesize = {},name = {}", page, pageSize, name);
        //参数封装
        Page pageInfo = new Page(page, pageSize);
        //封装查询条件
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(name)) {
            qw.like(Employee::getName, name);
        }
        employeeService.page(pageInfo, qw);

        List<Employee> records = pageInfo.getRecords();
        long total = pageInfo.getTotal();
        Map data = new HashMap<>();
        data.put("records", records);
        data.put("total", total);
        return R.success(data);
    }

    @PutMapping
    public R update(@RequestBody Employee employee) {

        log.info(employee.toString());

     /*   Employee loginUser = (Employee) request.getSession().getAttribute("loginUser");

        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(loginUser.getId());*/
        employeeService.updateById(employee);

        return R.success("修改信息成功");
    }

    @GetMapping("/{id}")
    public R getById(@PathVariable Long id) {
        Employee employee = employeeService.getById(id);
        if (employee != null) {
            return R.success(employee);
        }
        return R.error("没有查询到信息");
    }


}
